/* Cobber create 2024/04/14 */
const amqplib = require('amqplib/callback_api')
const { RABBIT_HOST, RABBIT_EX, RABBIT_QUEUE } = require('../config/rabbit.config')

const gContext = {
  connection: null,
  channel: null,
}

const initialize = (host) => {
    return new Promise((resolve, reject) => {
        amqplib.connect(host, (err, conn) => {
            if (err) {
                reject(err)
            } else {
                gContext.connection = conn
                conn.createChannel((err, ch) => {
                    if (err) {
                        reject(err)
                    } else {
                        gContext.channel = ch
                        resolve()
                        console.log('RabbitMQ initialized')
                    }
                })
            }
        })
    })
}

const publish = (ex, message) => {
    return new Promise((resolve, reject) => {
        gContext.channel.assertExchange(ex, 'topic', { durable: true }, (err, ok) => {
            if (err) {
                reject(err)
            } else {
                gContext.channel.publish(ex, 'ip.address', Buffer.from(JSON.stringify(message)))
                // console.log('publish', message)
                resolve()
            }
        })
    })
}

async function main() {
    try {
        let num = 0
        await initialize(RABBIT_HOST)
        
        while (num < 10000) {
            await publish(RABBIT_EX, { 
                timestamp: new Date().toISOString()
            }).catch((err) => {
                console.error(err, '=')
            })
            num++
        }
        
    } catch (err) {
        console.error(err)
    } finally {
        // if (gContext.connection) {
        //     gContext.connection.close()
        // }
    }
}

main()
